<template>
  <div class="page">
    <div class="topSearch">
      <div class="title"><span style="width: 3px;height: 20px;background-color:#0f79e2;margin-right: 8px"></span><span>单品出库</span>
      </div>
      <div class="search">
        <span>单名：</span>
        <el-input size="small" clearable style="width: 250px" v-model="singleName" placeholder="请输入采购单名"></el-input>
        <span>所属仓库：</span>
        <el-select clearable v-model="areaId" size='small'
                   style="width:250px" placeholder="请选择">
          <el-option v-for="item in warehouseList" :key="item.area" :label="item.areaName" :value='item.area' />
        </el-select>
        <span>选择日期：</span>
        <el-date-picker
          v-model="sateValue"
          type="daterange"
          range-separator="至"
          clearable
          size="small"
          @change="selectTime"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button size="small" type="primary" style="width: 80px;margin-left: 20px" @click="getOutportList">查询
        </el-button>
        <el-button size="small" style="width: 80px;margin-left: 20px" @click="reset">重置
        </el-button>
        <el-button size="small" type="primary" style="width: 100px;position: absolute;right: 40px" @click="addProduct">新增出库单</el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table :data="purchaseData" border height="calc(100vh - 350px)"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                v-loading='loading'
                :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}">
        <el-table-column prop="singleNo" label="单号" width="150px" />

        <el-table-column prop="singleName" label="单名" />
        <el-table-column label="产品明细" width="550px">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.list"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}"
              border
              style="width: 100%">
              <el-table-column prop="productCode" label="编码" />
              <el-table-column prop="productName" label="产品" width="200px" />
              <el-table-column prop="norms" label="规格" />
              <el-table-column prop="singleNum" label="数量" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="凭证">
          <template slot-scope="scope">
            <el-image v-for='(v, i) in scope.row.singleProof' :key="i" style="width: 50px; height: 50px"
                      ref="preview" :src="host+v" :preview-src-list="previewImg">

            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="所属仓库" width="190px">
          <template slot-scope="scope">
            <div class="warehouseTag" v-if="scope.row.areaId===46"
                 style="border:1px solid #f5b330;background-color:#fef7ea;color:#f5b330;"><img
              src="@/assets/svg/hubei.svg" class="warehouse_icon" /><span>宁乡贰</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===54"
                 style="border:1px solid #f5b330;background-color:#fef7ea;color:#f5b330;"><img
              src="@/assets/svg/hubei.svg" class="warehouse_icon" /><span>武汉仓</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===43"
                 style="border:1px solid #787cfc;background-color:#f1f2ff;color:#787cfc;"><img
              src="@/assets/svg/ningxiangyi.svg" class="warehouse_icon" /><span>宁乡壹</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===44"
                 style="border:1px solid #497ff4;background-color:#f1f5fe;color:#497ff4;"><img
              src="@/assets/svg/guangdong.svg" class="warehouse_icon" /><span>广东仓</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===45"
                 style="border:1px solid #4dc8ee;background-color:#edf9fd;color:#4dc8ee;"><img
              src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span>广西仓</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===52"
                 style="border:1px solid #00acf1;background-color:#e5f7f1;color:#00acf1;"><img
              src="@/assets/svg/yunnan.svg" class="warehouse_icon" /><span>贵州仓</span></div>
            <div class="warehouseTag" v-if="scope.row.areaId===53"
                 style="border:1px solid #4dc8ee;background-color:#edf9fd;color:#4dc8ee;"><img
              src="@/assets/svg/guangxi.svg" class="warehouse_icon" /><span>云南仓</span></div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="outInventory" label="是否出库">
          <template slot-scope="scope">
            <span v-if="scope.row.outInventory==0" style="color: #2cb5e8">未出库</span>
            <span v-if="scope.row.outInventory==1" style="color: #ebb563">已出库</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.outInventory!==1"
              @click="editOutport(scope.row)"
              style="color: #0f79e2;width: 100px;background-color:#e7f1fc;margin-top: 10px;cursor: pointer;text-decoration: none">
              编辑
            </el-link>
            <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              @confirm="optionPutInventory(scope.row)"
              icon-color="red"
              :title="`确定操作{`+scope.row.singleName+`}出库？`"
            >
              <el-link slot="reference"
                       style="color: #f5b330;width: 100px;background-color:#fef7ea;cursor: pointer"
                       v-if="scope.row.outInventory!==1">出库
              </el-link>
            </el-popconfirm>
          </template>

        </el-table-column>

      </el-table>
    </div>
    <el-pagination style="padding: 20px 0;" align="right" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>
    <!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线--><!--    分割线-->

    <el-dialog
      :title="title"
      :visible.sync="addDialog"
      width="60%"
      center
      :show-close="false"
      :before-close="handleClose">
      <div style="display: flex;align-items: center;margin-bottom: 30px;">
        <div style="width:80px;text-align: center;"><span style="color:red;">*</span>单名：</div>
        <el-input size="small" v-model="addForm.singleName" style="width: 36%"></el-input>
        <div style="width:80px;text-align: center;margin-left: 20px"><span style="color:red;">*</span>创建时间：</div>
        <el-date-picker
          :disabled="disabled"
          v-model="addForm.createTime"
          type="date"
          size="small"
          style="width: 36%">
        </el-date-picker>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 30px;">
        <div style="width:80px;text-align: center;"><span style="color:red;">*</span>出库仓库：</div>
        <el-select clearable v-model="addForm.areaId" size='small'
                   :disabled="disabled"
                   style="width:36%" placeholder="请选择" @change="changeFactoryInventory">
          <el-option v-for="item in warehouseList" :key="item.area" :label="item.areaName" :value='item.area' />
        </el-select>
        <div style="width:80px;text-align: center;margin-left: 20px">备注：</div>
        <el-input size="small" v-model="addForm.remark" style="width: 36%"></el-input>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 50px">
        <div style="width:80px;text-align: center;margin-top: 30px">凭证：</div>
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in preSalesImg' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="preSalesImgList">
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      分割线-->
      <el-table :data="factoryInventoryData" border max-height="300px"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                :headerCellStyle="{
'textAlign': 'center',
'fontWeight': 400,
'background': '#66b1ff',
'color': 'white',
}">
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="norms" label="规格" />
        <el-table-column label="出库数量">
          <template slot-scope="scope">
            <el-input-number :min="0" v-model="scope.row.singleNum"
                             @change="countChange"
                             size="small"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialog = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
    </el-dialog>


  </div>
</template>


<script>
import axios from 'axios';
import Decimal from 'decimal.js';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      pageNumber: 1,
      singleName: "",
      factoryId: "",
      optionType: "",
      areaId: "",
      title: "",
      disabled: false,
      startTime: "",
      endTime: "",
      productCode: "",
      productId: "",
      totalCount: 0,
      host: this.$imgHost,
      warehouseId: "",
      factoryName: "",
      sateValue: "",
      editSingleId: "",
      loading: false,
      allCount: "",
      addDialog: false,
      addForm: {},
      warehouseList: [],
      preSalesImg: [],
      preSalesImgList: [],
      previewImg: [],
      factoryList: [],
      purchaseData: [],
      factoryInventoryData: []
    }
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
    const params = {
      pageSize: 100000,
      pageNumber: 1
    }
    this.$api.areaLedgerAreaList(params).then(res => {
      this.warehouseList = res
    })
    this.$api.factoryGetFactoryList().then(res => {
      this.factoryList = res
    })
    this.getOutportList()
  },
  methods: {
    handleChange(val) {
    },
    handleClose() {
    },
    changeFactoryInventory(val) {
      this.$api.inventoryGetInventoryGoodsList({ areaId: val }).then(res => {
        if (res) {
          res.forEach(el => {
            el.singleNum = 0
          })
        }
        this.factoryInventoryData = res
      })
    },
    selectTime(val) {
      if (val) {
        this.startTime = dayjs(val[0]).format("YYYY-MM-DD");
        this.endTime = dayjs(val[1]).format("YYYY-MM-DD");
      } else {
        this.startTime = ''
        this.endTime = ''
      }
    },
    //操作入库
    optionPutInventory(val) {
      console.log(val)
      const data = {
        singleNo: val.singleNo,
        areaId: val.areaId
      }
      this.$api.singleSingleOutInventory(data).then(res => {
        if (res === 1) {
          this.$message({ message: "操作成功", type: "success" })
          this.getOutportList()
        }
      })
    },
    //单品出库列表
    getOutportList() {
      this.loading = true
      const data = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        areaId: this.areaId,
        singleName: this.singleName,
        startTime: this.startTime,
        endTime: this.endTime
      }
      this.$api.singleGetSingleList(data).then(res => {
        res.data.forEach(el => {
          if (el.singleProofStr) {
            // el.purchaseProofList = el.purchaseProof.split(',')
            el.singleProof.forEach(val => {
              this.previewImg.push('https://' + val)
            })
          } else {
            // el.purchaseProofList = [el.purchaseProof]
            // el.purchaseProofList.forEach(val => {
            //   this.previewImg.push('https://' + val)
            // })
          }
        })
        this.loading = false
        this.purchaseData = res.data
        this.totalCount = res.total
      })
    },
    submit() {
      if (!this.addForm.singleName || !this.addForm.areaId) {
        return this.$message({ message: "请检查必填项！" })
      }
      this.addForm.createTime = dayjs(this.addForm.createTime).format("YYYY-MM-DD")
      // const filteredList = this.factoryInventoryData.filter(item => item.purchaseNum !== 0 && item.warehousePosition);  //采购数量和库位必填
      const filteredList = this.factoryInventoryData.filter(item => item.singleNum !== 0); //采购数量必填，库位非必填
      const selectedFieldsArray = filteredList.map(product => ({
        materialId: product.materialId,
        productCode: product.productCode,
        productName: product.productName,
        singleNum: product.singleNum,
        norms: product.norms
      }));

      if (this.optionType == 1) {
        const data = {
          ...
            this.addForm,
          singleProof: this.preSalesImg,
          list: selectedFieldsArray,
        }
        this.$api.singleAddSingle(data).then(res => {
          if (res) {
            this.$message({ message: "新增成功", type: "success" })
            this.addDialog = false
            this.getOutportList()
          }
        })
      } else if (this.optionType == 2) {
        const data = {
          ...
            this.addForm,
          singleProof: this.preSalesImg,
          list: selectedFieldsArray,
          singleNo: this.editSingleId
        }
        this.$api.singleUpdateSingle(data).then(res => {
          if (res) {
            this.$message({ message: "操作成功", type: "success" })
            this.addDialog = false
            this.getOutportList()
          }
        })
      }

    },
    addProduct() {
      this.addDialog = true
      this.title = "新增出库单"
      this.disabled = false
      this.optionType = 1
      this.preSalesImg = this.$options.data.call(this).preSalesImg
      this.addForm = this.$options.data.call(this).addForm
      this.factoryInventoryData = []
    },
    handlePaste(event) {
      if (!this.addDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
        .then(response => {
          this.preSalesImg.push(response.data.result[0]);
          this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch(error => {
        });
    },
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getOutportList()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getOutportList()
    },
    reset() {
      this.pageSize = 20
      this.pageNumber = 1
      this.areaId = ''
      this.singleName = ''
      this.startTime = ''
      this.endTime = ''
      this.getOutportList()
    },
    editOutport(row) {
      this.title = '编辑'
      this.optionType = 2
      this.disabled = true
      this.addDialog = true
      this.editSingleId = row.singleNo
      this.addForm = {
        singleName: row.singleName,
        remark: row.remark,
        createTime: row.createTime,
        areaId: row.areaId
      }
      if (row.singleProof) {
        row.singleProof.forEach(el => {
          this.preSalesImgList.push(this.host + el)
        })
        this.preSalesImg = row.singleProof
      }
      this.$api.inventoryGetInventoryGoodsList({ areaId: row.areaId }).then(res => {
        //将接口返回的产品数量替换成row的数量
        res.forEach(el => {
          let match = row.list.find(val => val.productName === el.productName);
          if (match) {
            el.singleNum = match.singleNum
            // 标记替换的数据
            el.replaced = true;
          } else {
            el.singleNum = 0
            //false为不标记
            el.replaced = false;
          }
        })
        //将row.singleNum替换过的数据排在列表的前面
        res.sort((a, b) => b.replaced - a.replaced);
        this.factoryInventoryData = res
      })
    },
    countChange() {
      this.factoryInventoryData.forEach(el => {
        if (!el.singleNum) {
          el.singleNum = 0
        }
      })
    }

  }
}


</script>
<style lang='less' scoped>
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }

}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}

.centerTable {
  margin-top: 20px;
}

.warehouseTag {
  display: flex;
  justify-content: center;
  height: 30px;
  //width: 120px;
  margin: 0 28px 0 28px;
  align-items: center;
  border-radius: 50px;
}

.warehouse_icon {
  width: 20px;
  height: 20px;
  margin-right: 3px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

</style>
